package com.laowang.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.laowang.common.utils.gt.RSAUtil;
import com.laowang.common.utils.gt.SHA256;
import com.laowang.common.utils.http.HttpKit;
import com.laowang.common.utils.http.HttpUtil2;
import com.laowang.project.pay.config.MyWxPayConfigUtil2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;

/**
 * @Auther laowang
 * @Date 2022/7/28
 * @Description
 */

@Slf4j
public class PayUtil2 {

    //public static final String requestUrl= "https://yyfsvxm.postar.cn";
    public static final String requestUrl= "http://jghwucyshtgjcbrnxgwe.gtxygroup.com/testterpay";



    public static void main(String[] args) throws InterruptedException, ExecutionException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException, IOException {
        //getCustInfo("wangjian01","800528000020968","15","1.0.0","583567EA36FA617DF704269634E0971A");
        //pubSigPay(null,null,null,null,null,null,null,null);
        //test2();
        //test3();
        //test5();

        //orderQuery(new MyWxPayConfigUtil());
        //MyWxPayConfigUtil myWxPayConfigUtil = new MyWxPayConfigUtil("","800528000020975","7D258A5EA5949FE4EB0B4FB9F5A4C88B","15","88183559",new Date(),"599","1560512968397946880","20220819142419232545","","");
        //refund(myWxPayConfigUtil);
        String str= "0080055100005605932023051009450124547215MD516561130769125212168833515020230510104228V1.0.0F3A9B8509031A381DAF11718326986C1";
        String sign = DigestUtils.md5DigestAsHex(str.getBytes());
        System.out.println(sign);
        //999ad5986ecc490d49ebca37523aa9f2
        //999ad5986ecc490d49ebca37523aa9f2
    }


    /**
     * 小程序支付接口
     * @param myWxPayConfigUtil
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     * @throws IOException
     */
    public static Map<String,String> test4(MyWxPayConfigUtil2 myWxPayConfigUtil) throws InterruptedException, ExecutionException,  IOException {

        String url  ="https://yyfsvxm.postar.cn/yyfsevr/order/pay";
        TreeMap<String, String> params = new TreeMap<>();

        params.put("agetId", myWxPayConfigUtil.getAgetId() /*"1"*/);//商户所在国通系统内机构号
        params.put("custId",myWxPayConfigUtil.getCustId());//商户所在国通系统内商户号
        params.put("orderNo",myWxPayConfigUtil.getOrderNo());//订单号
        params.put("txamt", myWxPayConfigUtil.getTxamt()/*"1"*/);//订单金额单位分
        params.put("openid",myWxPayConfigUtil.getOpenid());
        params.put("payWay","1");//1.微信支付（小程序） 2.支付宝支付 3.银联支付 4.京东白条
        params.put("wxAppid",myWxPayConfigUtil.getAppId());
        params.put("traType","8");//5公众号 8小程序
        params.put("ip",myWxPayConfigUtil.getIp());
        params.put("version","V1.0.0");

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        params.put("timeStamp",now);
        //System.out.println(params);
        // 拼接参数，生成sign
        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        String res = sb.substring(0, sb.lastIndexOf("&"));
        log.info("拼接的待签名串：{}", res);
        String sha256 = SHA256.getSHA256(res);
        String sign = RSAUtil.encrypt(myWxPayConfigUtil.getPublicKey(), sha256);
        params.put("sign", sign);
        String paramJson = JSONObject.toJSONString(params);
        //String url = "xxx";
        // 发送请求
        String result = HttpUtil2.postData(url, paramJson);


        System.out.println("报文:"+paramJson);
        //String result = HttpKit.post(url, paramJson);

        Map<String,String> map = JSONObject.parseObject(result, Map.class);
        log.error("小程序支付map:{}",map);

        return map;
    }
/**
     * 小程序支付接口
     * @param myWxPayConfigUtil
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     * @throws IOException
     */
    public static Map<String,Object> test5(MyWxPayConfigUtil2 myWxPayConfigUtil)  {

        String url  ="https://yyfsvxm.postar.cn/yyfsevr/order/pay";
        //String url  ="https://yyfsvxm-g2-only.postar.cn/yyfsevr/order/pay";//测试 cacerts 是否包含国通星驿新服务器证书的根 CA（DigiCert Global Root CA 或 DigiCert Global Root G2）
        TreeMap<String, String> params = new TreeMap<>();

        params.put("agetId", myWxPayConfigUtil.getAgetId() /*"1"*/);//商户所在国通系统内机构号
        params.put("custId",myWxPayConfigUtil.getCustId());//商户所在国通系统内商户号
        params.put("orderNo",myWxPayConfigUtil.getOrderNo());//订单号
        params.put("txamt", myWxPayConfigUtil.getTxamt()/*"1"*/);//订单金额单位分
        params.put("openid",myWxPayConfigUtil.getOpenid());
        params.put("payWay","1");//1.微信支付（小程序） 2.支付宝支付 3.银联支付 4.京东白条
        params.put("wxAppid",myWxPayConfigUtil.getAppId());
        params.put("traType","8");//5公众号 8小程序
        params.put("ip",myWxPayConfigUtil.getIp());
        params.put("version","V1.0.0");

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        params.put("timeStamp",now);
        //System.out.println(params);
        // 拼接参数，生成sign
        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        String res = sb.substring(0, sb.lastIndexOf("&"));
        log.info("拼接的待签名串：{}", res);
        String sha256 = SHA256.getSHA256(res);
        String sign = RSAUtil.encrypt(myWxPayConfigUtil.getPublicKey(), sha256);
        params.put("sign", sign);
        String paramJson = JSONObject.toJSONString(params);
        //String url = "xxx";
        // 发送请求
        String result = HttpUtil2.postData(url, paramJson);


        System.out.println("报文:"+paramJson);
        //String result = HttpKit.post(url, paramJson);

        Map<String,Object> map = JSONObject.parseObject(result, Map.class);
        log.error("小程序支付map:{}",map);

        return map;
    }


    /**
     * 公众号支付接口
     * @param myWxPayConfigUtil
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     * @throws IOException
     */
    public static Map<String,Object> test8(MyWxPayConfigUtil2 myWxPayConfigUtil)  {

        String url  ="https://yyfsvxm.postar.cn/yyfsevr/order/pay";
        //String url  ="https://yyfsvxm-g2-only.postar.cn/yyfsevr/order/pay";//测试 cacerts 是否包含国通星驿新服务器证书的根 CA（DigiCert Global Root CA 或 DigiCert Global Root G2）
        TreeMap<String, String> params = new TreeMap<>();

        params.put("agetId", myWxPayConfigUtil.getAgetId() /*"1"*/);//商户所在国通系统内机构号
        params.put("custId",myWxPayConfigUtil.getCustId());//商户所在国通系统内商户号
        params.put("orderNo",myWxPayConfigUtil.getOrderNo());//订单号
        params.put("txamt", myWxPayConfigUtil.getTxamt()/*"1"*/);//订单金额单位分
        params.put("openid",myWxPayConfigUtil.getOpenid());
        params.put("payWay","1");//1.微信支付（小程序） 2.支付宝支付 3.银联支付 4.京东白条
        params.put("wxAppid",myWxPayConfigUtil.getWxOpenId());//公众号id
        params.put("traType","5");//5公众号 8小程序
        params.put("ip",myWxPayConfigUtil.getIp());
        params.put("version","V1.0.0");

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        params.put("timeStamp",now);
        //System.out.println(params);
        // 拼接参数，生成sign
        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        String res = sb.substring(0, sb.lastIndexOf("&"));
        log.info("拼接的待签名串：{}", res);
        String sha256 = SHA256.getSHA256(res);
        String sign = RSAUtil.encrypt(myWxPayConfigUtil.getPublicKey(), sha256);
        params.put("sign", sign);
        String paramJson = JSONObject.toJSONString(params);
        //String url = "xxx";
        // 发送请求
        String result = HttpUtil2.postData(url, paramJson);


        System.out.println("报文:"+paramJson);
        //String result = HttpKit.post(url, paramJson);

        Map<String,Object> map = JSONObject.parseObject(result, Map.class);
        log.error("小程序支付map:{}",map);

        return map;
    }

    /**
     * 小程序退款
     * @param myWxPayConfigUtil
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     * @throws IOException
     */
    public static Map<String,String> refound(MyWxPayConfigUtil2 myWxPayConfigUtil)  {

        String url  ="https://yyfsvxm.postar.cn/yyfsevr/order/refund";
        //String url  ="https://yyfsvxm-g2-only.postar.cn/yyfsevr/order/pay";//测试 cacerts 是否包含国通星驿新服务器证书的根 CA（DigiCert Global Root CA 或 DigiCert Global Root G2）
        TreeMap<String, String> params = new TreeMap<>();

        params.put("orderNo",myWxPayConfigUtil.getOrderNo());//订单号
        params.put("agetId", myWxPayConfigUtil.getAgetId() /*"1"*/);//商户所在国通系统内机构号
        params.put("custId",myWxPayConfigUtil.getCustId());//商户所在国通系统内商户号
        params.put("refundAmount", myWxPayConfigUtil.getTxamt()/*"1"*/);//退款金额单位分
        params.put("tag","2");//1支付宝 2微信 9银联或
        //params.put("payWay","1");//1.微信支付（小程序） 2.支付宝支付 3.银联支付 4.京东白条
        //params.put("wxAppid",myWxPayConfigUtil.getAppId());
        //params.put("traType","8");//5公众号 8小程序
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        params.put("timeStamp",now);
        //params.put("ip",myWxPayConfigUtil.getIp());
        params.put("version","V1.0.0");

        //System.out.println(params);
        // 拼接参数，生成sign
        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        String res = sb.substring(0, sb.lastIndexOf("&"));
        log.info("拼接的待签名串：{}", res);
        String sha256 = SHA256.getSHA256(res);
        String sign = RSAUtil.encrypt(myWxPayConfigUtil.getPublicKey(), sha256);
        params.put("sign", sign);
        String paramJson = JSONObject.toJSONString(params);
        //String url = "xxx";
        // 发送请求
        String result = HttpUtil2.postData(url, paramJson);


        System.out.println("报文:"+paramJson);
        //String result = HttpKit.post(url, paramJson);

        Map<String,String> map = JSONObject.parseObject(result, Map.class);
        log.error("小程序退款map:{}",map);

        return map;
    }




    /**
     *  订单分账
     * @param myWxPayConfigUtil
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     * @throws IOException
     */
    public static Map<String,Object> test6(MyWxPayConfigUtil2 myWxPayConfigUtil) throws InterruptedException, ExecutionException,  IOException {

        String url  ="https://yyfsvxm.postar.cn/yyfsevr/order/account";
        TreeMap<String, String> params = new TreeMap<>();

        params.put("agetId", myWxPayConfigUtil.getAgetId() /*"1"*/);//商户所在国通系统内机构号
        params.put("custId",myWxPayConfigUtil.getCustId());//商户所在国通系统内商户号
        params.put("orderNo",myWxPayConfigUtil.getOrderNo());//订单号
        params.put("areaId", myWxPayConfigUtil.getTxamt()/*"1"*/);//商圈编号
        params.put("accModel","1");//1自定义 2非自定义，默认传输1自定义
        params.put("accWay","1");//1日终-自定义分账、 3延迟-自定义分账
        params.put("orderAccDetail","");//{"ACC_DETAIL":[{"ACC_CUST_ID":"60000000000012","ACC_DATE":"0.1"}]}
        //ACC_CUST_ID: 需要从这笔交易中获得对应资金的600商户号， 全局唯一，不唯一则失败
        //ACC_DATE 单位为元，保留小数点最多2位
        params.put("timeStamp","");//时间戳
        params.put("version","");//版本
        params.put("sign","V1.0.0");//验签

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        params.put("timeStamp",now);
        //System.out.println(params);
        // 拼接参数，生成sign
        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        String res = sb.substring(0, sb.lastIndexOf("&"));
        log.info("拼接的待签名串：{}", res);
        String sha256 = SHA256.getSHA256(res);
        String sign = RSAUtil.encrypt(myWxPayConfigUtil.getPublicKey(), sha256);
        params.put("sign", sign);
        String paramJson = JSONObject.toJSONString(params);
        //String url = "xxx";
        // 发送请求
        String result = HttpUtil2.postData(url, paramJson);


        System.out.println("报文:"+paramJson);
        //String result = HttpKit.post(url, paramJson);

        Map<String,Object> map = JSONObject.parseObject(result, Map.class);
        log.error("小程序分账map:{}",map);

        return map;
    }


















    /**
     *  获取商户信息
     * @param custLogin    登入号
     * @param custId     	商户编号
     * @param agetId      	机构号
     * @param version      	版本号
     * @param sign          验签
     */
    public static void getCustInfo(String custLogin,String custId,String agetId,String version,String sign){
        Map<String,String> params = new HashMap<>();
        params.put("custLogin",custLogin);
        params.put("custId",custId);
        params.put("agetId",agetId);
        params.put("version",version);
        params.put("sign",sign);
        try {
            String res = HttpKit.get(requestUrl, params);
            System.out.println("res:"+res);
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    /**
     * 利用java原生的类实现SHA256加密
     *
     * @param str 加密后的报文
     * @return
     */
    public static String getSHA256(String str) {
        MessageDigest messageDigest;
        String encodestr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodestr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodestr;
    }
    /**

     将byte转为16进制



     @param bytes

     @return

     */

    private static String byte2Hex(byte[] bytes) {

        StringBuffer stringBuffer = new StringBuffer();

        String temp = null;

        for (int i = 0; i < bytes.length; i++) {

            temp = Integer.toHexString(bytes[i] & 0xFF);

            if (temp.length() == 1) {

                stringBuffer.append("0");

            }

            stringBuffer.append(temp);

        }

        return stringBuffer.toString();

    }


}
